﻿using System.Collections.Generic;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace FunstreamTV.Tools
{

    public class QualityItem
    {
        public string Quality { get; set; }
        public string StreamLink { get; set; }
    }

    public class TwitchToken
    {
        public string token { get; set; }
        public string sig { get; set; }
        public bool mobile_restricted { get; set; }
    }

    public static class Twitch
    {
        public static async Task<List<QualityItem>> GetM3U8(string channel)
        {
            List<QualityItem> playlist = new List<QualityItem>();

            string token = await GetToken(channel);
            using (HttpClient client = new HttpClient())
            {
                var uri = $"http://usher.twitch.tv/api/channel/hls/{channel}.m3u8?{token}";
                var s = await client.GetStringAsync(uri);
                var lines = s.Split('\n');
                string currentStreamName = "";
                foreach (var line in lines)
                {
                    var m = Regex.Matches(line, @"NAME=""(.*?)""");
                    if (m.Count > 0)
                    {
                        currentStreamName = m[0].Groups[1].Value;
                    }
                    if (line.Contains("http://"))
                    {
                        playlist.Add(new QualityItem { Quality = currentStreamName, StreamLink = line });
                    }
                }
            }
            return playlist;
        }

        private static async Task<string> GetToken(string channel)
        {
            string token = "";
            using (HttpClient client = new HttpClient())
            {
                var json = await client.GetStringAsync($"http://api.twitch.tv/api/channels/{channel}/access_token");
                var twitchToken = JsonConvert.DeserializeObject<TwitchToken>(json);
                token = $"token={twitchToken.token}&sig={twitchToken.sig}";
            }
            return token;
        }
    }
}
